#-*- coding: utf-8 -*-

import char_inputs
import classify
from converter import Converter, convert

# try:
#     import psyco
#     psyco.full()
#     print "Psyco on!"
# except ImportError:
#     print "No psyco."

def conv_lookup(centroids,distance,converters):
    def conv_lookup_template(token):
        conv_idx = classify.argmin(centroids,distance,classify.vector(token.lower(),char_inputs.weights))
        return converters[conv_idx]
    return conv_lookup_template

class ClusterConverter(object):
    def __init__(self, distance, centroids, converters):
        self.converters = converters
        #self.distance = classify.eucl_distance
        self.centroids = centroids
        #self.lookup = conv_lookup(distance, centroids, converters)
    
    def convert_text(self, text, lookup=None):
        distance = classify.eucl_distance
        if lookup == None: 
            lookup = conv_lookup( self.centroids, distance, self.converters)
        
        return convert(lookup, text)

    def convert_word(self, word):
        distance = classify.eucl_distance
        conv_idx = classify.argmin(self.centroids,distance,classify.vector(word.lower(),char_inputs.weights))
        return self.converters[conv_idx].convert(word)

def print_usage():
    print """  Greeklish converter by Orestis Markou
    usage: python main.py [options] greeklish-words
    example 1 - first use: python main.py -d my_data_%s.data -g greek.txt -r grkl.txt Na ena mikro paradeigma.
    example 2 - subsequent uses: python main.py -d my_data_%s.data Na ena mikro paradeigma.
    
    Description: Converts greeklish words into greek, using HMMs.
                 Before conversion can be done, an HMM data file needs to be created.
                 To create an HMM data file you'll have to provide a greeklish word file 
                 and a greek word file, in the format specified below.
                 You also have the option to use more than one cluster of words, for better results.
                 The default number of clusters is 10.
                 
    [options]
    -g, --greekwordfile filename:  filename must be a word file in the format
                                   greekword - count - (frequency)
                                   default: greek.txt
                                   
    -r, --grklwordfile filename:   filename must be a word file in the format
                                   greeklish - greek - number -
                                   default: grkl.txt
                                   
    -d, --datafile filename:       the filename will be the file that the hmm training
                                   data will be loaded from, or stored to if it doesn't exist.
                                   It has to include %s somewhere, that will be replaced with 
                                   the cluster number
                                   default: test%s.data
                                   
    -c, --cluster_format:          The name format that will be used for storing the cluster data.
                                   It has to include %s somewhere, that will be replaced with 
                                   the cluster number
                                   default: cl_.+[datafile]
                                   
    -n, --number_of_clusters:      The number of clusters that will be used in the HMM
                                   default: 10
                                   
    -h, --help: prints this text
    """
    
import sys
import getopt


    
def main_(_argv): 
    # print _argv
    _train = False
    datafile = None
    greekwordfile = None
    grklwordfile = None
    number_of_clusters = 10
    cluster_format = None 
    timing = False
    if(not _argv): print_usage(); sys.exit(2)
    try:                                
        opts, args = getopt.getopt(_argv, "hg:r:d:c:n:t", 
            ["help", "greekwordfile=", "grklwordfile=", "datafile=", 
            "cluster_format=", "number_of_clusters=", "timeit"]) 
    except getopt.GetoptError:           
        print_usage()                          
        sys.exit(2) 
    for opt, arg in opts:                
        if opt in ("-h", "--help"):      
            print_usage()                     
            sys.exit()   
        elif opt in ("-t", "--timeit"):      
            print "Timing!" 
            import time
            timing = True         
        elif opt in ("-g", "--greekwordfile"): 
            greekwordfile = arg   
        elif opt in ("-r", "--grklwordfile"): 
            grklwordfile = arg
        elif opt in ("-d", "--datafile"): 
            datafile = arg              
        elif opt in ("-c", "--cluster_format"): 
            cluster_format = arg                          
        elif opt in ("-n", "--number_of_clusters"): 
            number_of_clusters = int(arg)
    
    if not datafile: datafile = 'test%s.data'    
    if not cluster_format: cluster_format = 'cl_.'+datafile  
    if not greekwordfile: greekwordfile = 'greek.txt'
    if not grklwordfile: grklwordfile = 'grkl.txt'
    print "Training..." 
    conv = train_cluster(datafile,greekwordfile,grklwordfile,number_of_clusters,cluster_format)
    #print args   
    input = [arg.replace('\\n', '\n') for arg in args]
    #print input
    print "Converting..." 
    if timing:
        times = range(1)
        t1 = time.clock()
        for i in times:
            res =  conv.convert_text(''.join(input))
        t2 = time.clock()
        rt = round(t2-t1, 3)
        print "Time was:",rt
        print "Average time per char:",rt/(50.0*len(''.join(input)))
    else:
        res =  conv.convert_text(''.join(input))
    
    print res[0].encode('utf-8')
    print '---'
    for key in res[1]:
        print key.encode('utf-8'),':',res[1][key]
    
import char_inputs
import alignment
from model import *
def train_cluster(datafile,greekwordfile,grklwordfile,number_of_clusters,cluster_format):
    try:
        print datafile%('master',)
        cluster_conv = read_model(datafile%('master',))
    except:
        print "Creating model..."
        distance = classify.eucl_distance
        align_function = alignment.align3
        split_function = alignment.split_smart
        
        
        centroids = classify.classify_words(grklwordfile,    
                       distance , number_of_clusters, 
                       cluster_format,
                       char_inputs.weights, 10, {}, 10)
        converters=[]
        for i in range(0,len(centroids)): 
            conv = Converter(datafile%str(i),greekwordfile, cluster_format%str(i), align=align_function, split=split_function)
            converters.append(conv)
    
        cluster_conv = ClusterConverter(distance, centroids, converters)
        
        dump_model(cluster_conv,datafile%('master',))
    
    return cluster_conv

            

if __name__ == '__main__':
    print "from main"
    main_(sys.argv[1:])